<?php
/**
 * 备货申请（备货单）
 * (model)
 */
namespace App\Models\Stocking;

use App\Models\Basics\SysArea;
use App\Models\Product\ProductClassify;
use App\Models\Product\ProductSku;
use Illuminate\Database\Eloquent\Model;
class StockingApply extends Model
{
    protected $table = 's_stocking_apply';

    protected $guarded = [];

    public static $_status = [
        1 => '已审核',
        2 => '已关闭',
    ];

    public static $_planStatus = [
        1 => '未计划',
        2 => '部分计划',
        3 => '完全计划',
    ];

    public static $_purStatus = [
        1 => '未下单',
        2 => '已下单',
        3 => '已关闭',
    ];

    public static $_reStatus = [
        1 => '未到货',
        2 => '部分到货',
        3 => '完全到货',
    ];

    public function detail(){
        return $this->hasMany(StockingApplyDetail::class,'stocking_no','stocking_no');
    }

    public function area(){
        return $this->belongsTo(SysArea::class,'area_id');
    }

    public function sku(){
        return $this->belongsTo(ProductSku::class,'psku_id');
    }

    public function skuClassify(){
        return $this->hasOneThrough(
            ProductClassify::class,
            ProductSku::class,
            'id',//中间表
            'id',//目标表
            'psku_id',//当前模型
            'classify_id'//中间表
        );
    }

    protected static function boot()
    {
        parent::boot();

        static::deleting(function ($model){
            $detailStatus = $model->detail->max('status');
            if($detailStatus != 1){
                throw new \Exception('已生成下游单据勿删除');
            }else{
                $model->detail()->delete();
            }
        });
    }
}
